package shc.graduation.http.query;

import android.os.Handler;
import android.os.Looper;

import java.util.ArrayList;
import java.util.List;

import shc.graduation.bean.StateEvent;
import shc.graduation.http.listener.QueryListener;

/**
 * Created by shuhuiChen on  2016/5/21  18:31.
 * Email ：shuhuiCSH@126.com
 */
public abstract class BaseQuery<T> implements Runnable {

    public Handler mHandler = new Handler(Looper.getMainLooper());

    public int limit = 10;

    public List<T> mListModel = null;

    public StateEvent mStateEvent;
    private QueryListener mQueryListener;

    public BaseQuery() {
        mListModel = new ArrayList<>();
    }

    public void setStateEvent(StateEvent stateEvent) {
        this.mStateEvent = stateEvent;
    }

    public void setQueryListener(QueryListener listener) {
        this.mQueryListener = listener;
    }

    @Override
    public void run() {
        query();
    }

    public void callBackSuccess(final StateEvent stateEvent, final String info) {
        if (mQueryListener != null) {

            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mQueryListener.querySuccess(stateEvent, info);
                }
            });
        }
    }

    public void callBackFail(final StateEvent stateEvent, final String info) {
        if (mQueryListener != null) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mQueryListener.queryFail(stateEvent, info);
                }
            });
        }
    }

    public abstract void query();

    public void clear() {
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        if (mQueryListener != null) {
            mQueryListener = null;
        }

        if (mStateEvent != null) {
            mStateEvent = null;
        }
    }

}
